(function () {
    var exports = this;

    var $ = null;

    var HUTYPE_LIUJU = 0;
    var HUTYPE_ZIMO = 1;
    var HUTYPE_DIANPAO = 2;
    var HUTYPE_JIESAN = 3;

    var relationInfo = null;

    var playerRelation = function (players) {
        var ret = {};
        if (players.length == 2) {
            ret[players[0].uid] = {};
            ret[players[0].uid]['2'] = players[1].uid
            ret[players[1].uid] = {};
            ret[players[1].uid]['2'] = players[0].uid
        } else if (players.length == 3) {
            ret[players[0].uid] = {};
            ret[players[0].uid]['1'] = players[1].uid
            ret[players[0].uid]['-1'] = players[2].uid
            ret[players[1].uid] = {};
            ret[players[1].uid]['1'] = players[2].uid
            ret[players[1].uid]['-1'] = players[0].uid
            ret[players[2].uid] = {};
            ret[players[2].uid]['1'] = players[0].uid
            ret[players[2].uid]['-1'] = players[1].uid
        } else if (players.length == 4) {
            ret[players[0].uid] = {};
            ret[players[0].uid]['1'] = players[1].uid
            ret[players[0].uid]['2'] = players[2].uid
            ret[players[0].uid]['-1'] = players[3].uid
            ret[players[1].uid] = {};
            ret[players[1].uid]['1'] = players[2].uid
            ret[players[1].uid]['2'] = players[3].uid
            ret[players[1].uid]['-1'] = players[0].uid
            ret[players[2].uid] = {};
            ret[players[2].uid]['1'] = players[3].uid
            ret[players[2].uid]['2'] = players[0].uid
            ret[players[2].uid]['-1'] = players[1].uid
            ret[players[3].uid] = {};
            ret[players[3].uid]['1'] = players[0].uid
            ret[players[3].uid]['2'] = players[1].uid
            ret[players[3].uid]['-1'] = players[2].uid
        }
        ret.playerLength = players.length;
        return ret;
    }
    var relationshop = {
        '0': "",
        '1': '下家',
        '2': '对家',
        '-1': '上家'
    }
    var lengthToNumJia = function (len) {
        if (len == 2) {
            return "对家"
        } else if (len == 3) {
            return "两家"
        } else {
            return "三家"
        }
        return '';
    }
    var getZiByType = function (type) {
        switch (type) {
            case 1:
                return "自摸";
            case -1:
                return "被自摸";
            case 3:
                return "胡";
            case -3:
                return "点炮";
            case 5:
                return "查叫";
            case -5:
                return "被查叫";
        }
    }
    var getPlayer2PlayerRelation = function (uid1, uid2) {
        if (!relationInfo)return 0;
        if (uid2 == null) {
            return lengthToNumJia(relationInfo.playerLength)
        }
        if (_.isArray(uid2) && uid2.length >= 2) {
            return lengthToNumJia(uid2.length + 1)
        } else if (_.isArray(uid2) && uid2.length == 1) {
            uid2 = uid2[0];
        }
        var obj = relationInfo[uid1];
        for (var key in obj) {
            if (obj[key] == uid2) {
                return relationshop[key];
            }
        }
        return '';
    }
    var JiesuanLayer_lnbj = cc.Layer.extend({
        onEnter: function () {
            cc.Layer.prototype.onEnter.call(this);
        },
        ctor: function (data) {
            this._super();
            var that = this;

            var scene = loadNodeCCS(res.JiesuanLayer_lnbj_json, that);
            $ = create$(this.getChildByName("Scene"));

            var isZimo = (data['hu_type'] == HUTYPE_ZIMO);
            var isLiuju = (data['hu_type'] == HUTYPE_LIUJU);
            var isDianpao = (data['hu_type'] == HUTYPE_DIANPAO);
            var isJieSan = (data['hu_type'] == HUTYPE_JIESAN);
            var zhuangUid = data['zhuang'];

            var btnFenxiang = $('root.panel.btn_fenxiang');
            var btnStart = $('root.panel.btn_start');
            var btnChakan = $('root.panel.btn_chakan');


            var players = data.players;

            var huCnt = 0;
            var diangangMap = {};
            for (var i = 0; i < players.length; i++) {
                var player = players[i];
                var isHu = player['hu'];
                if (isHu) {
                    huCnt += 1;
                }

                var duiArr = player['dui_arr'];
                for (var j = 0; j < duiArr.length; j++) {
                    var dui = duiArr[j];
                    if (dui['from_uid'] && dui['from_uid'] != player.uid) {
                        diangangMap[dui['from_uid']] = diangangMap[dui['from_uid']] || 0;
                        diangangMap[dui['from_uid']]++;
                    }
                }
            }

            var my_score = 0;
            relationInfo = playerRelation(players);
            var rowInfoIdx = {}
            var playerMap = {};
            var myShowData = {};
            var gouchengArr = {}
            var showStrings = {};
            for (var i = 0; i < players.length; i++) {
                rowInfoIdx[players[i].uid] = 0;
                myShowData[players[i].uid] = {}
                playerMap[players[i].uid] = players[i];
                players[i].index = i;
                gouchengArr[players[i].uid] = []
            }

            for (var i = 0; i < players.length; i++) {
                var player = players[i];
                var uid = player['uid'];
                var score = player['score'];
                var gangScore = player['gang_score'];//杠分
                var fan = player['fan'];
                var paiArr = player['pai_arr'];
                var dingArr = player['dingArr'];
                var duiArr = player['dui_arr'];
                var textArr = player['text_arr'];
                var isHu = player['hu'];
                var huType = player['hu_type'];
                var hupaiId = player['hupai_id'];

                var paiIdArr = [];

                if ($('root.panel.row' + i))
                    $('root.panel.row' + i).setVisible(true);

                if (isHu) {
                    var idx = paiArr.indexOf(hupaiId);
                    if (idx >= 0) {
                        paiArr.splice(idx, 1);
                    }
                }

                var playerInfo = gameData.getPlayerInfoByUid(uid);
                $('root.panel.row' + i + '.lb_nickname').setString(ellipsisStr(playerInfo.nickname, 5));
                $('root.panel.row' + i + '.sp_zhuang').setVisible(zhuangUid == uid);
                $('root.panel.row' + i + '.lb_id').setString("ID: " + playerInfo.uid);

                $('root.panel.row' + i + '.bg').setVisible(gameData.uid != uid);
                $('root.panel.row' + i + '.bg_self').setVisible(gameData.uid == uid);

                loadImageToSprite(playerInfo.headimgurl, $('root.panel.row' + i + '.head'),true);

                if (uid == gameData.uid) my_score = score;


                //删除摆牌
                if (player['baiPai'].length > 0) {
                    for(var x=0; x<player['baiPai'].length; x++){
                        var fidx = paiArr.indexOf(player['baiPai'][x]);
                        if(fidx>=0) {
                            paiArr.splice(fidx,1)
                        }
                    }
                }

                while (true) {
                    for (var j = 0; j < duiArr.length; j++) {
                        var dui = duiArr[j];
                        if (dui.type == 5)
                            break;
                    }
                    if (j == duiArr.length)
                        break;
                    paiArr.push(duiArr[j]['pai_arr'][0]);
                    paiArr.push(duiArr[j]['pai_arr'][0]);
                    paiArr.push(duiArr[j]['pai_arr'][0]);
                    duiArr.splice(j, 1);
                }

                _.remove(paiArr, function (n) {
                    return n == 0;
                });

                paiArr.sort(function (a, b) {
                    return a - b
                });
                var _laizi_arr = [];
                if (data.laizi && data.laizi >= 0) {
                    _laizi_arr.push(data.laizi);
                }
                if (data.laizi2 && data.laizi2 >= 0) {
                    _laizi_arr.push(data.laizi2);
                }
                if (_laizi_arr.length > 0) {
                    for (var j = 0; j < _laizi_arr.length; j++) {
                        var oldSize = paiArr.length;
                        _.pull(paiArr, _laizi_arr[j]);
                        if (paiArr.length != oldSize) {
                            var t = paiArr.length;
                            for (var k = 0; k < oldSize - t; k++)
                                paiArr.splice(0, 0, _laizi_arr[j]);
                        }
                    }
                }
                duiArr.sort(function (a, b) {
                    if (a['pai_arr'][0] == b['pai_arr'][0]) {
                        if (a['pai_arr'][1] == b['pai_arr'][1])
                            return a['pai_arr'][2] - b['pai_arr'][2];
                        return a['pai_arr'][1] - b['pai_arr'][1];
                    }
                    return a['pai_arr'][0] - b['pai_arr'][0];
                });

                var a0 = $('root.panel.row' + i + '.a' + 0);
                var anGangCnt = 0;
                var gangCnt = 0;
                for (var j = 0; j < duiArr.length; j++) {
                    var dui = duiArr[j];
                    if (dui.type == 1 || dui.type == 2) {
                        paiIdArr.push(dui['pai_arr'][0]);
                        paiIdArr.push(dui['pai_arr'][1]);
                        paiIdArr.push(dui['pai_arr'][2]);
                        paiIdArr.push(-2);
                    }
                    if (dui.type == 3) {
                        paiIdArr.push(dui['pai_arr'][0]);
                        paiIdArr.push(dui['pai_arr'][0]);
                        paiIdArr.push(dui['pai_arr'][0]);
                        paiIdArr.push(dui['pai_arr'][0]);
                        gangCnt++;
                        paiIdArr.push(-1);
                    }
                    if (dui.type == 4) {
                        paiIdArr.push(0);
                        paiIdArr.push(0);
                        paiIdArr.push(0);
                        paiIdArr.push(dui['pai_arr'][0]);
                        anGangCnt++;
                        paiIdArr.push(-1);
                    }
                }

                for (var j = 0; j < paiArr.length; j++) {
                    paiIdArr.push(paiArr[j]);
                }

                if (player['baiPai'].length > 0) {
                    paiIdArr.push(-4);
                    paiIdArr = paiIdArr.concat(player['baiPai']);
                }

                // 血战
                if (isHu && hupaiId && hupaiId != 0) {
                    paiIdArr.push(-3);
                    paiIdArr.push(hupaiId);
                }

                if (textArr && textArr.length > 0) {
                    //gouchengArr = [];
                    gouchengArr[uid].push('[')
                    for (var j = 0; j < textArr.length; j++) {
                        var obj = textArr[j];
                        for (var key in obj) {
                            if (obj.hasOwnProperty(key)) {
                                if (decodeURIComponent(key) == "杠") {
                                    gouchengArr[uid].push(decodeURIComponent(key) + ('x' + obj[key]));
                                } else {
                                    gouchengArr[uid].push(decodeURIComponent(key) + (obj[key] > 1 ? 'x' + obj[key] : ''));
                                }
                            }
                        }
                    }
                    gouchengArr[uid].push(']')
                    //设置其余玩家信息
                    // cc.log(gouchengArr)
                }

                var exceBei = function (_info, uid) {
                    cc.log("exceBei", _info, uid);
                    var tdata = null
                    if (!myShowData[_info.uid][uid]) {
                        tdata = {};
                        myShowData[_info.uid][uid] = tdata;
                        tdata.types = [-tinfo.type];
                        tdata.scores = [-tinfo.score]
                        tdata.uids = [uid]
                    } else {
                        tdata = myShowData[_info.uid][uid]
                        tdata.types.push(-tinfo.type);
                        tdata.scores.push(-tinfo.score);
                        tdata.uids.push(uid)
                    }
                }
                //上家 对家 下家分数显示
                var scoreInfo = player['score_relate'] || [];
                scoreInfo.sort(function (a, b) {
                    return a.type - b.type;
                })
                // var myShowData = {};
                var lastType = null;
                var lastUid = null;
                for (var x = 0; x < scoreInfo.length; x++) {
                    var tinfo = scoreInfo[x];
                    var tdata = null
                    if (tinfo.type == lastType) {
                        // lastUid = tinfo.uid;
                        tdata = myShowData[uid][lastUid]
                        tdata.types.push(tinfo.type);
                        tdata.scores.push(tinfo.score);
                        tdata.uids.push(tinfo.uid);
                        lastType = tinfo.type;
                        exceBei(tinfo, uid)
                        continue;
                    } else {
                        lastUid = tinfo.uid;
                    }
                    if (!myShowData[uid][tinfo.uid]) {
                        tdata = {};
                        myShowData[uid][tinfo.uid] = tdata;
                        tdata.types = [tinfo.type];
                        tdata.scores = [tinfo.score];
                        tdata.uids = [tinfo.uid]
                    } else {
                        tdata = myShowData[uid][tinfo.uid]
                        tdata.types.push(tinfo.type);
                        tdata.scores.push(tinfo.score);
                        tdata.uids.push(tinfo.uid);
                    }
                    lastType = tinfo.type;
                    exceBei(tinfo, uid)
                }
                // cc.log(myShowData);
                var gapNum = 0;
                var gapDistance = 8;
                var isBai = false;
                var offNum = 0;
                for (var j = 0; j < paiIdArr.length; j++) {
                    if (paiIdArr[j] == -1) {
                        gapNum++;
                        var pai = $('root.panel.row' + i + '.a' + (j - 1));
                        if (pai) {
                            pai.x -= a0.getContentSize().width * a0.getScaleX() * 2;
                            pai.y += 10;
                        }
                        cc.log(paiIdArr, j);
                        offNum+=2;
                        continue;
                    } else if (paiIdArr[j] == -3) {
                        gapNum++;
                        offNum++;
                        isBai = false;
                        cc.log(paiIdArr, j);
                        continue;
                    } else if (paiIdArr[j] == -2) {
                        gapNum++;
                        offNum++;
                        continue;
                    } else if(paiIdArr[j] == -4) {
                        isBai = true;
                        gapNum++;
                        offNum++;
                        continue;
                    }
                    var pai = $('root.panel.row' + i + '.a' + j);
                    if (!pai) {
                        pai = duplicateNode(a0);
                        pai.setName('a' + j);
                        pai.setPositionX(a0.getPositionX() + a0.getContentSize().width * a0.getScaleX() * (j -offNum) + gapNum * gapDistance);
                        a0.getParent().addChild(pai);

                        if(isBai){
                            var baiIcon = new cc.Sprite(majiang_gs.res['bai_png_' + 2]);
                            // sp.setPosition(cpg.getChildByName('sp_' + i).getPosition());
                            baiIcon.setName('bai');
                            baiIcon.x = a0.getContentSize().width/2 ;
                            baiIcon.y = a0.getContentSize().height +10;
                            pai.addChild(baiIcon);
                        }
                    }

                    var paiName = 'p2s' + paiIdArr[j] + '.png';
                    setSpriteFrameByName(pai, paiName, 'pai');
                }
            }
            //绘制节点
            for (var keyUid in myShowData) {
                var obj = myShowData[keyUid];
                for (var linekey in obj) {
                    var value = obj[linekey];
                    for (var x = 0; x < value.types.length; x++) {
                        var _type = value.types[x];
                        var _score = value.scores[x];
                        var _uid = value.uids[x];
                        var name = getZiByType(_type);
                        cc.log(x, keyUid, name, linekey, _score)
                        if (x > 0) {
                            cc.log("----", showStrings[keyUid][rowInfoIdx[keyUid]]);
                            if (value.types[0] == _type) {
                                showStrings[keyUid][rowInfoIdx[keyUid]].text = showStrings[keyUid][rowInfoIdx[keyUid]].text + " " + getPlayer2PlayerRelation(keyUid, _uid);
                                showStrings[keyUid][rowInfoIdx[keyUid]].score += _score;
                            } else {
                                showStrings[keyUid][rowInfoIdx[keyUid]].text = name + "," + showStrings[keyUid][rowInfoIdx[keyUid]].text;
                                showStrings[keyUid][rowInfoIdx[keyUid]].score += _score;
                            }

                        } else {

                            var gouchengStr = "";
                            if (!showStrings[keyUid]) {
                                showStrings[keyUid] = {}
                            }
                            if (!showStrings[keyUid][rowInfoIdx[keyUid]]) {
                                showStrings[keyUid][rowInfoIdx[keyUid]] = {};
                            }
                            if (_type > 0) {
                                if (gouchengArr[keyUid]) gouchengStr = gouchengArr[keyUid].join(" ")
                            } else {
                                if (gouchengArr[_uid]) gouchengStr = gouchengArr[_uid].join(" ")
                            }
                            cc.log(linekey, "gouchengStr ", gouchengArr[keyUid]);
                            showStrings[keyUid][rowInfoIdx[keyUid]].text = name + (gouchengStr) + " " + getPlayer2PlayerRelation(keyUid, _uid)
                            showStrings[keyUid][rowInfoIdx[keyUid]].score = _score
                        }
                    }
                    rowInfoIdx[keyUid]++;
                    cc.log("rowInfoIdx[keyUid] ", keyUid, "++");
                }
            }
            cc.log(showStrings);
            for (var i = 0; i < 4; i++) {
                for (var j = 0; j < 3; j++) {
                    $('root.panel.row' + i + '.lb_desp_' + j).setString("");
                    $('root.panel.row' + i + '.lb_score_sum_' + j).setString('');
                }
            }
            for (var uid in showStrings) {
                for (var i = 0; i < 3; i++) {
                    if (showStrings[uid][i]) {
                        $('root.panel.row' + playerMap[uid].index + '.lb_desp_' + i).setString(showStrings[uid][i].text || "");
                        $('root.panel.row' + playerMap[uid].index + '.lb_score_sum_' + i).setString(showStrings[uid][i].score > 0 ? "+" + showStrings[uid][i].score : showStrings[uid][i].score);
                    } else {
                        $('root.panel.row' + playerMap[uid].index + '.lb_desp_' + i).setString("");
                        $('root.panel.row' + playerMap[uid].index + '.lb_score_sum_' + i).setString('');
                    }
                }
            }

            if (isJieSan) {
                for (var i = 0; i < 3; i++) {
                    for (var j = 0; j < 3; j++) {
                        $('root.panel.row' + i + '.lb_desp_' + j).setString("");
                        $('root.panel.row' + i + '.lb_score_sum_' + j).setString('');
                    }
                }
                $('root.panel.title_jiesan').setVisible(true);
                $('root.panel.title_jiesan.title_jiesan').setVisible(true);

            } else if (isLiuju) {
                $('root.panel.title_jiesan').setVisible(true);
                $('root.panel.title_jiesan.title_liuju').setVisible(true);
            } else if (my_score > 0) {
                $('root.panel.title_win_bg').setVisible(true);
            } else {
                $('root.panel.title_fail_bg').setVisible(true);
                $('root.panel.title_fail_bg.title_zjzl').setVisible(true);
            }
            $('root.panel.lb_selfscore').setString(my_score > 0 ? "+" + my_score : my_score);

            $('root.panel.lb_ts').setString(timestamp2time(data['ts']));
            $('root.panel.lb_wanfatitle').setString("玩法:陇南摆叫");
            $('root.panel.lb_wanfa').setString(gameData.wanfaDesp);
            $('root.panel.lb_roomid').setString('房号: ' + gameData.roomId );
            $('root.panel.lb_jushu').setString('局数: ' + data['cur_round'] + '/' + data['total_round']);

            for (var i = players.length; i < 4; i++)
                $('root.panel.row' + i).setVisible(false);

            TouchUtil.setOnclickListener(btnFenxiang, function () {
                ShareUtil.SharePic(that);
            });

            TouchUtil.setOnclickListener(btnStart, function () {
                // ready
                network.send(3004, {room_id: gameData.roomId});
                window.maLayer.onJiesuanClose(true);
                that.removeFromParent(true);
            });

            var closeFunc = function () {
                // ready
                window.maLayer.onJiesuanClose(false);
                that.removeFromParent(true);
            };
            TouchUtil.setOnclickListener(btnChakan, closeFunc);

            if (data['is_last']) {
                btnStart.setVisible(false);
                btnChakan.setVisible(true);
            }

            return true;
        }
    });

    exports.JiesuanLayer_lnbj = JiesuanLayer_lnbj;
})(window);
